//
// Created on 2025/7/30.
//

#ifndef BLANKSCREENDETECTOR_BLANKSCREENDETECTOR_H
#define BLANKSCREENDETECTOR_BLANKSCREENDETECTOR_H

#pragma once
#include "BlankScreenTypes.h"
#include <chrono>

class BlankScreenDetector {
public:
    // 算法参数配置结构体
    struct AlgorithmParams {
        // 颜色相关参数
        struct ColorParams {
            static constexpr int GRAY_TOLERANCE_SQUARED = 144;           // 12^2，避免开方运算
            static constexpr int PRECHECK_COLOR_DISTANCE_SQUARED = 64;   // 8^2，预检查颜色距离平方
            static constexpr int UNIFORM_COLOR_DISTANCE_SQUARED = 36;    // 6^2，统一颜色距离平方
            static constexpr int TEXT_EDGE_THRESHOLD_SQUARED = 64;       // 8^2，文本边缘阈值平方
        };
        
        // 像素阈值参数
        struct PixelThresholds {
            static constexpr uint8_t WHITE_MIN = 245;     // 白色像素最小值
            static constexpr uint8_t BLACK_MAX = 8;       // 黑色像素最大值
            static constexpr double WHITE_LUMINANCE = 235.0;  // 白色亮度阈值
            static constexpr double BLACK_LUMINANCE = 20.0;   // 黑色亮度阈值
        };
        
        // 区域检测参数
        struct RegionParams {
            static constexpr double BLANK_REGION_MIN_UNIFORMITY = 0.90;        // 最小一致性
            static constexpr double BLANK_REGION_UNIFORMITY_TEXT_THRESHOLD = 0.95; // 文字检查阈值
            static constexpr double FLOOD_FILL_UNIFORMITY_THRESHOLD = 0.90;  // 块一致性阈值
            static constexpr double MIN_ASPECT_RATIO = 0.15;       // 最小宽高比
            static constexpr double MAX_ASPECT_RATIO = 6;       // 最大宽高比
            static constexpr double MIN_REGION_WIDTH_RATIO = 6;      // 最小区域宽度比例
            static constexpr double MIN_REGION_HEIGHT_RATIO = 10;    // 最小区域高度比例
        };
        
        // 采样参数
        struct SamplingParams {
            static constexpr int PRECHECK_SAMPLE_STEP = 16;       // 预检查采样步长
            static constexpr int REGION_SAMPLE_SIZE = 16;         // 区域检测采样大小
            static constexpr int PIXEL_COUNT_STEP = 2;            // 像素计数采样步长
            static constexpr int BLOCK_SAMPLE_STEP_DIVISOR = 4;   // 块采样步长除数
        };
        
        // 阈值参数
        struct ThresholdParams {
            static constexpr double PRECHECK_DETECTION_RATIO = 0.90;      // 预检查检测比例
            static constexpr double PRECHECK_SKELETON_GRAY_RATIO = 0.1;   // 骨架屏灰色最小比例
            static constexpr double PRECHECK_SKELETON_BG_RATIO = 0.5;     // 骨架屏背景色最小比例
            static constexpr double OVERALL_BLANK_THRESHOLD = 0.1;        // 整体空白阈值
            static constexpr double LARGE_REGION_THRESHOLD = 0.05;        // 大区域阈值
            static constexpr size_t MAX_DOMINANT_COLORS = 8;             // 最大主要颜色数
            static constexpr double COLOR_GRADIENT_THRESHOLD = 30; // 颜色梯度阈值
        };
        
        // 并行化参数
        struct ParallelParams {
            static constexpr int MIN_PIXELS_FOR_PARALLEL = 100000;  // 最小并行化像素数
            static constexpr int PARALLEL_CHUNK_SIZE = 4096;        // 并行块大小
            static constexpr int SIMD_ALIGN = 16;                   // SIMD对齐字节数
        };
    };

    DetectionResult detect(const uint8_t* pixelData, int width, int height, int bytesPerPixel);
    
private:
    // 优化1: 直接像素访问，零拷贝
    inline Pixel getPixelDirect(const uint8_t* pixelData, int x, int y, int width, int bytesPerPixel) const {
        const uint8_t* ptr = pixelData + (y * width + x) * bytesPerPixel;
        return Pixel(ptr[2], ptr[1], ptr[0], bytesPerPixel > 3 ? ptr[3] : 255);
    }
    
    // 优化1: 快速颜色分类，避免复杂计算
    inline int classifyColorFast(uint8_t r, uint8_t g, uint8_t b) const {
        if (r >= AlgorithmParams::PixelThresholds::WHITE_MIN && g >= AlgorithmParams::PixelThresholds::WHITE_MIN && b >= AlgorithmParams::PixelThresholds::WHITE_MIN) 
            return 1; // WHITE
        if (r <= AlgorithmParams::PixelThresholds::BLACK_MAX && g <= AlgorithmParams::PixelThresholds::BLACK_MAX && b <= AlgorithmParams::PixelThresholds::BLACK_MAX) 
            return 2; // BLACK
        
        int maxDiff = std::max({abs(r-g), abs(g-b), abs(r-b)});
        if (maxDiff * maxDiff <= AlgorithmParams::ColorParams::GRAY_TOLERANCE_SQUARED) 
            return 3; // GRAY
        return 0; // OTHER
    }
    
    // 优化1: 平方距离计算，避免开方
    inline int colorDistanceSquared(uint8_t r1, uint8_t g1, uint8_t b1, 
                                   uint8_t r2, uint8_t g2, uint8_t b2) const {
        int dr = r1 - r2;
        int dg = g1 - g2;
        int db = b1 - b2;
        return dr*dr + dg*dg + db*db;
    }
    
    // 优化8: 预计算安全边界，减少边界检查
    struct SafeBounds {
        int safeWidth;
        int safeHeight;
        int totalPixels;
        bool canUseParallel;
        
        SafeBounds(int width, int height, int step) 
            : safeWidth(width - step)
            , safeHeight(height - step)
            , totalPixels(width * height)
            , canUseParallel(totalPixels >= AlgorithmParams::ParallelParams::MIN_PIXELS_FOR_PARALLEL) {}
    };
    
    // 核心检测方法 - 直接操作原始数据
    DetectionResult performPrecheckDirect(const uint8_t* pixelData, int width, int height, int bytesPerPixel);
    std::vector<BlankRegion> detectRectangularRegionsDirect(const uint8_t* pixelData, int width, int height, int bytesPerPixel);
    DetectionResult generateFinalResult(const std::vector<BlankRegion>& regions, int width, int height);
    
    // 区域分析方法 - 直接数据访问
    BlankRegion sampleBasedFloodFillDirect(const uint8_t* pixelData, int width, int height, int bytesPerPixel,
                                          int startX, int startY, const Pixel& targetColor,
                                          std::vector<std::vector<bool>>& processed, int sampleSize);
    
    // 辅助方法 - 优化版本
    bool isSampleBlockUniformDirect(const uint8_t* pixelData, int width, int height, int bytesPerPixel,
                                   int blockX, int blockY, const Pixel& targetColor, int blockSize) const;
    int countActualPixelsDirect(const uint8_t* pixelData, int width, int height, int bytesPerPixel,
                               const Rectangle& bounds, const Pixel& targetColor) const;
    bool isAbnormalRectangular(const BlankRegion& region, int width, int height) const;
    
    // 优化6&7: 智能并行化处理
    template<typename Func>
    void processPixelsParallel(const uint8_t* pixelData, int width, int height, int bytesPerPixel,
                              const SafeBounds& bounds, Func processor) const;
    
    // 优化7: 向量化处理关键循环
    void processPixelBlockSIMD(const uint8_t* pixelData, int startIdx, int count, int bytesPerPixel,
                              int* colorCounts) const;
    
    // 结果生成辅助方法
    BlankRegion createFullScreenRegion(BlankType type, const Pixel& color, double confidence, 
                                     int width, int height) const;
    void collectDominantColors(const std::vector<BlankRegion>& regions, DetectionResult& result) const;
    void calculateStatistics(const std::vector<BlankRegion>& regions, int totalPixels, 
                           DetectionResult& result) const;
    
    // 性能监控
    mutable std::chrono::high_resolution_clock::time_point m_startTime;
    void startTiming() const { m_startTime = std::chrono::high_resolution_clock::now(); }
    long long getElapsedMicroseconds() const {
        auto endTime = std::chrono::high_resolution_clock::now();
        return std::chrono::duration_cast<std::chrono::microseconds>(endTime - m_startTime).count();
    }
};

#endif //BLANKSCREENDETECTOR_BLANKSCREENDETECTOR_H
